package aqua.smile.springboot.security.config;

import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author chujian
 * @since 2022-11-07 22:58
 **/
//@Configuration
public class SecurityConfig implements WebMvcConfigurer {

    // 默认URL,跳转到登录
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("redirect:/login");
    }

    /**
     * 默认注册一个密码编码器
     *
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(); // 比较常用的密码解析器
    }

    /**
     * 注入UserDetailService -> 提供用户服务（通过用户名查询用户）
     *
     * @return
     */
    @Bean
    public UserDetailsService userDetailsService(PasswordEncoder passwordEncoder) {
        InMemoryUserDetailsManager userDetailsManager =
                new InMemoryUserDetailsManager(
                        User.withUsername("admin")
                                .password(passwordEncoder.encode("admin"))
                                .authorities("admin")
                                .build(),
                        User.withUsername("admin2")
                                .password(passwordEncoder.encode("admin2"))
                                .authorities("admin")
                                .build(),
                        User.withUsername("user01")
                                .password(passwordEncoder.encode("user"))
                                .authorities("user")
                                .build()
                );

        return userDetailsManager;
    }

}
